Page({
  data: {
    dateLayerVisible: false, // 日期动作面板的显示/隐藏
    houseLayerVisible: false, // 房屋信息动作面板的显示/隐藏
    houseList: [],
    currentDate: Date.now(), // 当前时间戳
    maxDate: Date.now() + 3 * 24 * 3600 * 1000,
    houseInfo: '',

    houseId: '',
    visitDate: '',
    name: '',
    gender: 0,
    mobile: '',
  },

  onLoad() {
    this.getHouseList()
  },

  // 1. 打开和关闭选择房屋的动作面板
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  // 2. 打开和关闭日志的弹层
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  // 3. 去通行证页面
  goPassport() {
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index',
    })
  },

  // 4. 获取房屋列表信息
  async getHouseList() {
    // 4.1 调用获取房屋详情接口
    const { code, data: houseList } = await wx.http.get(`/house`)
    if (code !== 10000) return wx.util.toast('获取房屋列表失败')
    // 4.2 更新数据
    this.setData({ houseList })
  },

  // 5. 选择房屋信息
  selectHouse(ev) {
    const { id: houseId, name: houseInfo } = ev.detail
    this.setData({
      houseId,
      houseInfo,
    })
  },

  // 6. 选择访问日期
  selectDate(ev) {
    // console.log(ev.detail)
    this.setData({
      dateLayerVisible: false,
      visitDate: wx.utils.formatDate(ev.detail),
    })
  },

  // 7. 提交表单
  async submitForm() {
    const { houseInfo, mobile, name, visitDate, houseId, gender } = this.data
    // 7.1 校验
    if (!wx.verify.verifyHouse(houseInfo)) return
    if (!wx.verify.verifyName(name)) return
    if (!wx.verify.verifyMobile(mobile)) return
    if (!wx.verify.verifyDate(visitDate)) return

    // 7.2 调用接口
    const {
      code,
      data: { id },
    } = await wx.http.post('/visitor', { houseId, mobile, name, visitDate, gender })
    if (code !== 10000) return wx.utils.toast('填写访客信息失败')

    // 7.3 跳转到通行证页面
    wx.redirectTo({
      url: '/visitor_pkg/pages/passport/index?id=' + id,
    })
  },
})
